import { observable, action, autorun, toJS } from 'mobx';
import { WeaLocaleProvider } from 'ecCom';
import { WeaForm, WeaTableNew } from 'comsMobx'
import { message, Button, Modal } from "antd";
import * as Apis from '../../apis/info';
import { ListStore } from '../listStore';
import ResponseData from './data/responseData';
import { feedbackDialogStore } from '../dialog/feedbackDialogStore';
import { specialDialogStore } from '../dialog/specialDialogStore';
import { rewardDialogStore } from '../dialog/rewardDialogStore';
import { Text } from '../../components/util/text';
const text = new Text();

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
export default class infoHandleCardStore {

    @observable feedbackDialogStore = new feedbackDialogStore(this);
    @observable specialDialogStore = new specialDialogStore(this);
    @observable rewardDialogStore = new rewardDialogStore(this);
    @observable selectTabKey = "infoHandle";    //信息处理卡片默认选中
    @observable responseData = new ResponseData();
    @observable tableStore = new TableStore();  //反馈信息页签中反馈信息列表
    @observable scoreTableStore = new TableStore();      //历史分数列表store
    @observable dataSource = [];
    @observable columns = [];

    @observable form = new WeaForm();    //信息处理卡片form
    @observable condition = [];    //信息处理卡片condition
    @observable status = {
        loading: false,
        showTab: true,        //是否展示信息反馈页签(待编信息详情时不展示信息反馈)
        scoreVisible: false,   //历史分数弹出框
        quickVisible: false,  // 快捷筛选弹出框dialog
    }

    @observable quickSiftForm = new WeaForm();      //快捷筛选弹出框form
    @observable quickSiftCondition = new WeaForm();  //快捷筛选弹出框condition

    @observable isRight = false;        //判断是否有权限
	@observable loadingSpin = true;     //全局loading

    curid = "";
    siftId = "";
    jsonList = [];        //快捷加分按钮的json


    constructor(props) {
    }

    setState = (params = {}) => {
        Object.keys(params).forEach(o => {
            this.status[o] = params[o];
        })
        return this;
    }

    //初始化信息处理卡片
    @action
    getAddInfoTypeCondition = (params = {}) => {
        this.curid = params.id;
        this.siftId = params.siftId;
        this.status.loading = true;
        let newParams = { ...params };
        this.loadingSpin = true;
        Apis.getAddInfoTypeCondition(newParams).then(data => {
            if (data.api_status == '1') {
                this.loadingSpin = false;
                this.isRight = data.isRight;
                if (!this.isRight) {
                    return;
                }
                this.condition = data.infoConditionGroup;
                this.form = new WeaForm();
                this.form && !this.form.isFormInit && this.form.initFormFields(this.condition);
                this.responseData.rightMenus = data.rightMenus;
                this.jsonList = data.jsonList;
                this.status.loading = false;
                //this.responseData = { rightMenus: data.rightMenus };
            } else {
                message.error(data.api_errormsg);
            }

        })
    }

    //获取历史分数table
    @action
    getRewardListByInfoSiftId = (params = {}) => {
        Apis.getRewardListByInfoSiftId(params).then(data => {
            if (!data.isRight) {
                message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                return;
            }
            this.setState({ 'scoreVisible': true });
            this.scoreTableStore.getDatas(data.sessionkey, 1)
        });
    }

    //设置选中按钮
    changeTab = (key) => {
        this.selectTabKey = key;
        if (key == "infoHandle") {              //基本信息
        } else if (key == "infoFeedback") {     //信息反馈
            this.getInfoFeedbackList({ infoId: this.curid, by: 'tab' });    //by表示点击页签显示的反馈信息
        }
    }

    //得到信息反馈List
    @action
    getInfoFeedbackList = (params = {}) => {
        Apis.getInfoFeedbackList({ ...params }).then(data => {
            this.tableStore.getDatas(data.sessionkey, 1)
        })
    }

    getRightMenu = () => {
        const { rightMenus } = this.responseData;
        let btnArr = [];
        rightMenus && rightMenus.length > 0 && rightMenus.map(m => {
            btnArr.push({
                key: m.type,
                icon: <i className={m.menuIcon} />,
                content: m.menuName,
                onClick: key => {
                    this.buttonClick(key);
                }
            })

        });
        return btnArr;
    }
    /**
   * 上方按钮
   */
    getTopButton = () => {
        const { rightMenus } = this.responseData;
        let btnArr = [];
        this.jsonList && this.jsonList.length > 0 && this.jsonList.map((m,index) => {
            if (m.showInView == '1') {
                btnArr.push(
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2uf5a5@${index}`} style={{ marginLeft: "10px" }} type={"primary"}
                        onClick={() => {
                            let _this = this;
                            Modal.confirm({
                                title: text.SYSTEMTIP,
                                content: text.SUREADDSCORE,
                                onOk() {
                                    if (m.rewardType == '0') {
                                        let tableJson = [{ "id": m.rewardId, "type": 0 }]
                                        let params = { 'tableJson': JSON.stringify(tableJson), ids: _this.siftId };
                                        Apis.saveAddScore(params).then(result => {
                                            if (result.api_status == '1') {
                                                if (!result.isRight) {
                                                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                                    return;
                                                }
                                                if (typeof (result.msg) != 'undefined') {
                                                    message.error(result.msg);
                                                    return;
                                                }
                                                message.success(text.SAVESUCCESS);
                                                if (window.opener && window.opener._table && window.opener._table.reLoad) {
                                                    window.opener._table.reLoad();
                                                }
                                            } else {
                                                message.error(result.api_errormsg);
                                            }
                                        })
                                    }
                                    if (m.rewardType == '1' || m.rewardType == '2') {
                                        _this.rewardDialogStore.getRewardList({ 'rewardId': m.rewardId, 'type': '5' });
                                        _this.ids = _this.siftId;
                                        //_this.rewardDialogStore.setState({ visible: true });
                                    }
                                }
                            });

                        }}>
                        {m.showName}
                    </Button>
                );
            }
        });
        rightMenus && rightMenus.length > 0 && rightMenus.map((m,index) => {
            btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6te1pf@${index}`} style={{ marginLeft: "10px" }} type={"primary"}
                    onClick={() => {
                        this.buttonClick(m.type);
                    }}>
                    {m.menuName}
                </Button>
            );
        });
        return btnArr;
    }

    //删除历史加分记录
    @action
    delScore = (params = {}) => {
        let selectedRowKeys = this.scoreTableStore.selectedRowKeys;
        if (selectedRowKeys.length == 0) {
            message.warn(text.CHOOSERECORD);
            return;
        }
        let _this = this;
        Modal.confirm({
            title: text.SYSTEMTIP,
            content: text.SUREDELETE,
            onOk() {
                let newParams = { 'ids': selectedRowKeys.join(",") };
                Apis.deleteAddScore(newParams).then(data => {
                    if (data.api_status == '1') {
                        if (!data.isRight) {
                            message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                            return;
                        }
                        message.success(text.DELSUCCESS);
                        //刷新得分历史和已发布的待编信息table
                        _this.scoreTableStore.getDatas(_this.scoreTableStore.dataKey, _this.scoreTableStore.current, _this.scoreTableStore.pageSize, _this.scoreTableStore.sortParams);
                        if (window.opener && window.opener._table && window.opener._table.reLoad) {
                            window.opener._table.reLoad();
                        }
                    } else {
                        message.error(data.api_errormsg);
                    }
                });
            }
        });
    }

    //快捷筛选弹出框condition
    @action
    getQuickFilterDialogCondition = (params = {}) => {
        Apis.getQuickFilterDialogCondition(params).then(data => {
            if (data.api_status == '1') {
                if (!data.isRight) {
                    message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                    return;
                }
                this.status.quickVisible = true;
                this.quickSiftCondition = data.infoConditionGroup;
                this.quickSiftForm = new WeaForm();
                this.quickSiftForm && !this.quickSiftForm.isFormInit && this.quickSiftForm.initFormFields(this.quickSiftCondition);
            } else {
                message.error(data.api_errormsg);
            }

        });
    }

    //快捷筛选查询期刊
    @action
    searchJournal = (v) => {
        let formParams = this.quickSiftForm.getFormParams();
        if (formParams.j_type == '') {
            message.error("请选择刊型！");
            this.dataSource = [];
            return;
        }
        let newParams = { 'j_type': formParams.j_type, name: v || '' };
        Apis.getQuickJournalList(newParams).then(data => {
            if (data.api_status == '1') {
                this.dataSource = data.dataSource;
                this.columns = data.columns;
            } else {
                message.error(data.api_errormsg);
            }

        })
    }

	//保存快捷筛选
    @action
    saveQuickSift = (params = {}) => {
        let formParams = this.quickSiftForm.getFormParams();
        let newParams = { ...formParams, ...params, ids: this.curid };
        let _this = this;
        Apis.checkJournalType(newParams).then(data => {
            if (data.api_status == '1') {
                if (data.flag == true) {
                    message.error('该刊型已经被引用');
                } else {
                    this.quickSiftForm.validateForm().then(f => {
                        if (f.isValid) {
                            Apis.saveQuickFilter(newParams).then(data => {
                                if (data.api_status == '1') {
                                    if (!data.isRight) {
                                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                        return;
                                    }
                                    Modal.confirm({
                                        content: '快捷筛选成功，是否跳转至排版界面?',
                                        onOk() {
                                            _this.setState({ quickVisible: false });
                                            _this.getAddInfoTypeCondition({ id: _this.curid, siftId: _this.siftId });
                                            if (window.opener && window.opener._table && window.opener._table.reLoad) {
                                                window.opener._table.reLoad();
                                            }
                                            setTimeout(() => {
                                                openFullWindowForXtable('/spa/info/static/index.html#/main/info/composing?id=' + data.journalId + "&type=show&isSpecialReport=false&isQuickSift=true");
                                            }, 300);
                                        },
                                        onCancel() {
                                            _this.setState({ quickVisible: false });
                                            _this.getAddInfoTypeCondition({ id: _this.curid, siftId: _this.siftId });
                                            if (window.opener && window.opener._table && window.opener._table.reLoad) {
                                                window.opener._table.reLoad();
                                            }
                                         },
                                    });
                                } else {
                                    message.error(data.api_errormsg);
                                }
                            });
                        } else {
                            this.quickSiftForm.showError('j_type', '刊型栏目未填写完整');
                        }
                    });
                }
            } else {
                message.error(data.api_errormsg);
            }
        });
    }

    buttonClick(key) {
        if (key == "BTN_INFO_FEEDBACK") {            //信息反馈
            this.feedbackDialogStore.initFeedbackForm({ id: this.curid, typeNum: 1 });
            //this.feedbackDialogStore.setState({ visible: true });
        }
        if (key == "BTN_SAVE_TYPE") {             //保存刊型
            let formParams = this.form.getFormParams();
            let newParams = { ...formParams };
            if (formParams.j_type == '') {
                message.warn(text.TIP7);
                return;
            }
            Apis.saveInfoType(newParams).then(data => {
                if (data.api_status == '1') {
                    if (!data.isRight) {
                        message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                        return;
                    }
                    message.success(text.SAVESUCCESS);
                    if (window.opener && window.opener._table && window.opener._table.reLoad) {
                        window.opener._table.reLoad();
                    }
                } else {
                    message.error(data.api_errormsg);
                }
            })
        }
        if (key == 'BTN_SPECIAL_USE') {             //特殊采用
            this.specialDialogStore.getSpecialHandleCondition({ ids: this.curid, type: 'specialUse', by: 'card' });
            //this.specialDialogStore.setState({ visible: true });
        }
        if (key == 'BTN_SPECIAL_REPORT') {          //专报
            this.specialDialogStore.getSpecialHandleCondition({ ids: this.curid, type: 'specialReport', by: 'card' });
            //this.specialDialogStore.setState({ visible: true });
        }
        if (key == 'BTN_CANCEL_SPECIAL_USE') {      //取消特殊采用
            let _this = this;
            Modal.confirm({
                content: text.CANCELSPECIALUSE,
                onOk() {
                    Apis.cancelSpecialUse({ id: _this.curid }).then(data => {
                        if (data.api_status == '1') {
                            if (!data.isRight) {
                                message.error(getLabel(2012, '对不起，您暂时没有权限！'));
                                return;
                            }
                            message.success(text.CANCELSUCCESS);
                            window.opener._table.reLoad();
                            window.close();
                        } else {
                            message.error(data.api_errormsg);
                        }
                    });
                },
                onCancel() { },
            });
        }
        if (key == 'BTN_ADD_SCORE') {       //加分
            this.ids = this.siftId;
            this.getRewardListByInfoSiftId({ id: this.siftId });
            //this.setState({ 'scoreVisible': true });
        }

        if (key == 'BTN_QUICK_FILTER') {    //快捷筛选
            this.columns = [];
            this.dataSource = [];
            //this.setState({ quickVisible: true });
            this.getQuickFilterDialogCondition({ ids: this.curid });
        }
    }
}